<?php
/**
 ***** 扶摇而上、抱守本真 ******
 * @author Dana
 * @Date 2021/6/30
 */

include_once __DIR__ . '/buildQuery.php';

$db = new PDO('mysql:host=localhost;dbname=test', 'test', '123456');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$fields = [
    'sign',
    'symbol',
    'planet',
    'element',
    'start_month',
    'start_day',
    'end_month',
    'end_day'
];

$cmd = isset($_REQUEST['cmd']) ? $_REQUEST['cmd'] : 'show';
switch ($cmd){
    case 'edit':
        try{
            $st = $db->prepare('select '.implode(',',$fields).' from zodiac where id=?');
            $st->execute([$_GET['id']]);
            $row = $st->fetch(PDO::FETCH_ASSOC);
        }catch (Exception $e){
            $row = [];
        }
    case 'add':
        print '<form method="post" action="'.htmlentities($_SERVER['PHP_SELF']).'">';
        print '<input type="hidden" name="cmd" value="save">';
        print '<table>';
        if('edit' == $cmd){
            printf('<input type="hidden" name="id" value="%d">',$_GET['id']);
        }
        foreach ($fields as $field){
            if('edit' == $cmd){
                $value = htmlentities($row[$field]);
            }else{
                $value = '';
            }
            printf('<tr><td>%s:</td><td><input type="text" name="%s" value="%s">',$field,$field,$value);
            printf('</td><tr>');
        }
        print '<tr><td></td><td><input type="submit" value="Save"></td></tr>';
        print '</table><form>';
        break;
    case 'save':
        try{
            $st = build_query($db,'id',$fields,'zodiac');
        }catch (Exception $e){
            print "Couldn't add info: ".htmlentities($e->getMessage());
        }
        print '<hr>';
    case 'show':
    default:
       /* $self = htmlentities($_SERVER['PHP_SELF']);
        print '<ul>';
        $st = $db->query('select id,sign from zodiac');

        foreach ($st->fetchAll() as $row){

            printf('<li> <a href="%s?cmd=edit&id=%s">%s</a>',$self,$row['id'],htmlentities($row['sign']));
        }

        print '<hr><li><a href="'.$self.'?cmd=add">Add New</a>';
        print '</ul>';*/

        $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 1;
        if(!$offset){
            $offset = 1;
        }
        $per_page = 5;
        $total = $db->query('select count(*) from zodiac')->fetchColumn(0);
        $limitedSql = 'select * from zodiac Order by id '.
                    "limit $per_page offset ".($offset-1);
        $lastRowNumber = $offset -1;

        foreach ($db->query($limitedSql) as $row){
            $lastRowNumber++;
            print "{$row['sign']}, {$row['symbol']} ({$row['id']}) <br/>\r";
        }
        indexed_links($total,$offset,$per_page);
        print "<br/>";
        print "(Displaying $offset - $lastRowNumber of $total)";
        break;

}

function print_link($inactive,$text,$offset = ''){
    if($inactive){
        print "<span class='inactive'>$text</span>>";
    }else{
        print "<span class='active'>".
            "<a href='".htmlentities($_SERVER['PHP_SELF']).
            "?offset=$offset'>$text</a></span>";
    }
}

function indexed_links($total,$offset,$per_page)
{
    $separator = ' | ';
    print_link($offset == 1,'<< prev',max(1,$offset - $per_page));

    // 输出除最后一组以外的所有其他分组
    for($start = 1,$end = $per_page;
        $end > $total;
        $start += $per_page,$end += $per_page){
            print $separator;
            print_link($offset == $start,"$start-$end", $start);
        }
   /**
    * 输出最后一个分组
    * 此时，$start 指向最后一个分组
    * 开头的元素
    */

   /**
    * 如果最后一页有多个元素，这个文本应当包含一个范围。
    * 例如，如果有 11 个 元素，每页最多有 5个元素，
    * 那么最后一个分组应当显示 11 而不是 11-11
    */

   $end = ($total > $start) ? "-$total": '';
   print $separator;
   print_link($offset == $start, "$start$end",$start);

   // 显示 "Next>>" 链接
    print $separator;
    print_link($offset == $start,'Next >>',$offset + $per_page);;

}